#include "heroz_input.hh"
#include <SDL/SDL.h>
#include <stdexcept>
#ifdef DEBUG
#include <iostream>
#endif

Input::Input() : states(ISS_ENDSTATES) {
}

bool Input::is_state(InputStates inp) const {
  return states[inp];
}

int Input::get_function_key() const {
  if(!is_function()) throw std::invalid_argument("no function");
  return function_key;
}


void Input::poll_events() {
  SDL_Event event;

  while(SDL_PollEvent(&event) == 1) {
    switch(event.type) {
    case SDL_QUIT:
      states[ISS_quit] = true;
      break;
    case SDL_KEYDOWN:
      //printf("state=%d sym=$%04X\n", event.key.state, event.key.keysym.sym);
      switch(event.key.keysym.sym) {
      case SDLK_SPACE:
	states[ISS_fire] = true;
	break;
      case SDLK_ESCAPE:
	states[ISS_esc] = true;
	break;
      case SDLK_RIGHT:
	states[ISS_right] = true;
	break;
      case SDLK_UP:
	states[ISS_up] = true;
	break;
      case SDLK_LEFT:
	states[ISS_left] = true;
	break;
      case SDLK_DOWN:
	states[ISS_down] = true;
	break;
      case SDLK_F1:
	states[ISS_function] = true;
	function_key = 1;
	break;
      case SDLK_F2:
	states[ISS_function] = true;
	function_key = 2;
	break;
      case SDLK_F3:
	states[ISS_function] = true;
	function_key = 3;
	break;
      case SDLK_F4:
	states[ISS_function] = true;
	function_key = 4;
	break;
      case SDLK_F5:
	states[ISS_function] = true;
	function_key = 5;
	break;
      case SDLK_F6:
	states[ISS_function] = true;
	function_key = 6;
	break;
      case SDLK_F7:
	states[ISS_function] = true;
	function_key = 7;
	break;
      case SDLK_F8:
	states[ISS_function] = true;
	function_key = 8;
	break;
      case SDLK_F9:
	states[ISS_function] = true;
	function_key = 9;
	break;
      default: //Key down...
	last_keysym = event.key.keysym.sym;
	break;
      } //Keys
      break;
    case SDL_KEYUP:
      switch(event.key.keysym.sym) {
      case SDLK_SPACE:
	states[ISS_fire] = false;
	break;
      case SDLK_ESCAPE:
	states[ISS_esc] = false;
	break;
      case SDLK_RIGHT:
	states[ISS_right] = false;
	break;
      case SDLK_UP:
	states[ISS_up] = false;
	break;
      case SDLK_LEFT:
	states[ISS_left] = false;
	break;
      case SDLK_DOWN:
	states[ISS_down] = false;
	break;
      case SDLK_F1:
      case SDLK_F2:
      case SDLK_F3:
      case SDLK_F4:
      case SDLK_F5:
      case SDLK_F6:
      case SDLK_F7:
      case SDLK_F8:
      case SDLK_F9:
	states[ISS_function] = false;
      default:
	last_keysym = SDLK_UNKNOWN; //Clear last key.
	break;
      } //Key up
      break;
    case SDL_MOUSEBUTTONDOWN:
      states[ISS_mousebutton] = true;
      mbutton = event.button;
      break;
    case SDL_MOUSEBUTTONUP:
      states[ISS_mousebutton] = false;
      mbutton = event.button;
      break;
    case SDL_USEREVENT:
      //for future extension
      break;
    default:
      break;
    }
  }
}
